﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace Client
{
    class NetIO
    {
        string connect;
        int port;
        Socket socket;

        bool isRead = false, isWrite=false;

        byte[] data = new byte[1024];

        
        List<byte> cache = new List<byte>();    //缓冲

        List<TransModel> models = new List<TransModel>();


        public NetIO(string con,int p) {
            connect = con;
            port = p;
        }

        public void Start() {
            try {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(connect, port);

                socket.BeginReceive(data, 0, 1024, SocketFlags.None, ReceiveCallBack, this);

            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }


        void ReceiveCallBack(IAsyncResult  ar) {

            int length = socket.EndReceive(ar);

            if (length > 0) {
                byte[] value = new byte[length];

                Buffer.BlockCopy(data, 0, value, 0, value.Length);
                cache.AddRange(value);

                if (!isRead) {
                    isRead = true;
                    Read();
                }
            }
            
            try
            {
                //BeginReceive方法也要try catch
                socket.BeginReceive(data, 0, 1024, SocketFlags.None, ReceiveCallBack, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
        }

        /// <summary>
        /// 缓冲区cache的数据
        /// </summary>
        public void Read()
        {
            byte[] value = LengthE_D.LengthDecode(ref cache);
            if (value == null)
            {
                isRead = false;
                return;
            }
            else
            {
                TransModel m = (TransModel)TransModelE_D.TransDecode_de(value);
                if (m == null)
                {
                    isRead = false;
                    return;
                }

                //通知上层应用，消息到达
                //center.OnMessageReceive(this, model);
                //Console.WriteLine(model.GetMessage<byte>());
                //Console.WriteLine(model.GetMessage<NetIO>.ToString());
                Console.WriteLine(m.type + "  " + m.area + "  " + m.command + "  " + m.GetMessage<string>());
                Read(); //递归，继续读取消息
            }
        }

    }
}
